import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:kzcity_picker/kzcity_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/index.dart';
import 'package:yp/pages/address_create/widgets/text_input.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';
import 'package:yp/widgets/button_widget.dart';
import 'package:yp/widgets/dialog.dart';
import 'package:yp/widgets/index.dart';
import 'package:yp/pages/address_selector/cy_city_picker.dart';

import '../../city_information.dart';
import '../../helper.dart';

class ApplyExpert extends StatefulWidget {
  const ApplyExpert({Key key}) : super(key: key);

  @override
  _ApplyExpertState createState() => _ApplyExpertState();
}

class _ApplyExpertState extends State<ApplyExpert> with SingleTickerProviderStateMixin {
  List addressList;
  int sex = 1;
  bool isSelect = false;

  // String provinceName = '';
  // String cityName = '';
  // String areaName = '';
  // int provinceId = 320000;
  // int cityId = 320300;
  // int areaId = 320303;
  String provinceName = '';
  String cityName = '';
  String areaName = '';
  String townName = '';
  // int provinceId = 0;
  // int cityId = 0;
  // int areaId = 0;
  // int twonId = 0;
  String provinceId = "";
  String cityId = "";
  String areaId = "";
  String townId = "";

  Map province = {'name': '', 'id': ''};
  Map city = {
    'name': '',
    'id': '',
  };
  Map district = {
    'name': '',
    'id': '',
  };
  Map street = {
    'name': '',
    'id': '',
  };
  var provinceList = [];
  var cityList = [];
  var cityAreaList = [];
  var townList = [];

  var detail = {};
  int userNumid;
  String html = '';
  String agreement_name = '';

  /// 选择地址
  // void selectCity(value) {
  //   setState(() {
  //     provinceName = value.province;
  //     cityName = value.city;
  //     areaName = value.area;
  //     provinceId = int.parse(value.provinceCode);
  //     cityId = int.parse(value.cityCode);
  //     areaId = int.parse(value.areaCode);
  //     townId = int.parse(value.townCode);
  //     controller3.text = value.province + ' ' + value.city + ' ' + value.area;
  //   });
  // }
  void selectCity(int index, Map checkedItem, List backAddressItemList) {
    switch (index) {
      case 0:
        province = checkedItem;
        provinceList = backAddressItemList;

        city = {};
        cityList = [];
        district = {};
        cityAreaList = [];
        street = {};
        townList = [];

        break;
      case 1:
        city = checkedItem;
        cityList = backAddressItemList;

        district = {};
        cityAreaList = [];
        street = {};
        townList = [];

        break;
      case 2:
        district = checkedItem;
        cityAreaList = backAddressItemList;

        street = {};
        townList = [];

        break;
      case 3:
        street = checkedItem;
        townList = backAddressItemList;
        break;
    }

    if (index == 3) {
      provinceName = province["name"];
      cityName = city["name"];
      areaName = district["name"];
      townName = street["name"];
      provinceId = province["id"];
      cityId = city["id"];
      areaId = district["id"];
      townId = street["id"];

      controller3.text = provinceName +' '+ cityName+' '+ areaName + (townName == null ? "" : (" " + townName));
      // update();
      setState(() {});
    }
  }

  //提交申请
  getapplysubmit() {
    var params = {
      'mber_type': 0,
      'apply_scenario': 1,
      'leader_usr_num_id': SpUtil.getInt('empeNumId'),
      'usr_name': _phoneController.text,
      'invite_mobile_phone': _higherPhoneController.text, //上级手机号
      'birthday': _birthdayController.text, //生日
      "prv_num_id": provinceId,
      "city_num_id": cityId,
      "city_area_num_id": areaId,
      "town_num_id": townId,
      "access_token": SpUtil.getString('token'),
    };
    print("state.group_buy_item.runtimeType.toString()");
    print(params);
    Api.applysubmit(params).listen((event) {
      if (event['code'] == 0) {
        Get.toNamed(RouteConfig.expertUnderReview);
      }
    });
  }

  getCity() {
    var cityParams = {
      "access_token": SpUtil.getString('token'),
    };
    Api.cityInformation(cityParams).listen((event) {
      // print('城市信息  event = $event');
      if (event['code'] == 0) {
        AddressInformation addressInformation = AddressInformation.fromJson(event);
        Map<String, dynamic> mapData = addressInformation.toJson();
        addressList = mapData['children'];
      }
    });
  }

  AnimationController _controller;

  //收货人所在地区
  TextEditingController controller3 = TextEditingController();
  TextEditingController _nameController = TextEditingController(); //姓名
  TextEditingController _phoneController = TextEditingController(); //自己手机号
  TextEditingController _higherPhoneController = TextEditingController(); //上级手机号
  TextEditingController _higherNumController = TextEditingController(); //上级编号
  TextEditingController _birthdayController = TextEditingController(); //生日

  bool _agree = false;

  @override
  void initState() {
    print('传参');
    print(Get.arguments);
    setState(() {
      if (Get.arguments != null) {
        _nameController.text = Get.arguments['usr_name'];
        _phoneController.text = Get.arguments['mobile'];
        if (Get.arguments['prv_name'] != null) {
          provinceName = Get.arguments['prv_name'] + Get.arguments['city_name'] + Get.arguments['city_area_name'];
          controller3.text = Get.arguments['prv_name'] + Get.arguments['city_name'] + Get.arguments['city_area_name'];
          provinceId = Get.arguments['prv_num_id'];
          cityId = Get.arguments['city_num_id'];
          areaId = Get.arguments['city_area_num_id'];
          townId = Get.arguments['town_num_id'];
        }
      }
    });

    Api.agreen1({"data_sign": 0, "channel_num_id": 98, "use_platform": 3, "access_token": SpUtil.getString('token'), "agreement_key": "service_agreement_koc"}).listen((event) {
      // print('城市信息  event = $event');
      if (event['code'] == 0) {
        setState(() {
          agreement_name = event['service_agreement']['agreement_name'];
          html = event['service_agreement']['agreement_value'];
        });
      }
    });
    super.initState();
    _controller = AnimationController(vsync: this);
  }

  void _clickEventFunc(context) async {
    // final res = await KzcityPicker.showPicker(
    //   context,
    //   datas: addressList,
    // );
    // if (res != null) {
    //   // 刷新
    //   selectCity(res);
    // }

    XYZCityPicker.showPicker(
        province: province,
        city: city,
        district: district,
        street: street,
        provinceListBack: provinceList,
        cityListBack: cityList,
        cityAreaListBack: cityAreaList,
        townListBack: townList,
        context: context,
        onChange: (int index, Map checkedItem, List backAddressItemList) {
          selectCity(index, checkedItem, backAddressItemList);
        });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: YPNavigationBar('申请成为慧达人'),
      body: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: Column(
              children: [
                _item('申请人姓名', '请输入申请人姓名', _nameController, must: true),
                _item('申请人手机号', '请输入申请人手机号', _phoneController, must: true),
                Container(
                  color: EsColors.White,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Padding(
                        padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
                        child: Row(children: [
                          Visibility(visible: true, child: Text('*', style: TextStyle(color: EsColors.Primary, fontSize: EsSizes.SM, fontWeight: EsFontWeights.Normal))),
                          SizedBox(width: false ? 90 : 110, child: Text("所在地区", style: TextStyle(color: EsColors.ContentSecondary, fontSize: EsSizes.SM, fontWeight: EsFontWeights.Normal))),
                          GestureDetector(
                            onTap: () {
                              _clickEventFunc(context);
                            },
                            child: provinceName == ''
                                ? Text(
                                    "请选择地址",
                                    style: TextStyle(
                                      fontSize: 28.sp,
                                      color: Color(0xffcccccc),
                                    ),
                                  )
                                : Text(
                                    controller3.text,
                                    style: TextStyle(
                                      fontSize: 28.sp,
                                      color: Color(0xff333333),
                                    ),
                                  ),
                          ),
                        ]),
                      ),
                      Visibility(visible: true, child: YpLine())
                    ],
                  ),
                ),
                _item('上级手机号', '请输入上级手机号', _higherPhoneController),
                // 所在地区
                // TextInputWidget(
                //   title: "所在地区",
                //   suffixWidget: GestureDetector(
                //     onTap: () {
                //       _clickEventFunc(context);
                //     },
                //     child: Row(
                //       mainAxisAlignment: MainAxisAlignment.end,
                //       children: [
                //        provinceName == ''
                //             ? Text(
                //                 "请选择地址",
                //                 style: TextStyle(
                //                   fontSize: 28.sp,
                //                   color: Color(0xffcccccc),
                //                 ),
                //               )
                //             : Text(
                //                controller3.text,
                //                 style: TextStyle(
                //                   fontSize: 28.sp,
                //                   color: Color(0xff333333),
                //                 ),
                //               ),
                //         Icon(
                //           Icons.arrow_forward_ios_rounded,
                //           color: Color(0xffcccccc),
                //           size: 14,
                //         )
                //       ],
                //     ),
                //   ),
                // ),
                _item('生日', '请输入您的生日', _birthdayController, line: false),
                _protocol()
              ],
            ),
          )
        ],
      ),
      floatingActionButton: _bottom(),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }

  Widget _item(String title, String tips, TextEditingController _editingController, {bool must = false, bool line = true}) {
    return Container(
      color: title != '申请人手机号' ? EsColors.White : Colors.grey[200],
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(12, 0, 12, 0),
            child: Row(children: [
              Visibility(visible: must, child: Text('*', style: TextStyle(color: EsColors.Primary, fontSize: EsSizes.SM, fontWeight: EsFontWeights.Normal))),
              SizedBox(width: must ? 90 : 98, child: Text(title, style: TextStyle(color: EsColors.ContentSecondary, fontSize: EsSizes.SM, fontWeight: EsFontWeights.Normal))),
              Expanded(
                child: TextField(
                  enabled: title != '申请人手机号', //禁用
                  decoration: InputDecoration(hintText: tips, fillColor: Colors.transparent),
                  controller: _editingController,
                  onChanged: (info) {
                    setState(() {});
                  },
                ),
              ),
            ]),
          ),
          Visibility(visible: line, child: YpLine())
        ],
      ),
    );
  }

  Widget _protocol() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        setState(() {
          _agree = !_agree;
        });
      },
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Row(children: [
          Image.asset(
            _agree ? 'assets/images/select2.png' : 'assets/images/select1.png',
            width: 14,
            height: 14,
          ),
          SizedBox(width: 8),
          RichText(
              text: TextSpan(children: [
            TextSpan(text: '我已阅读并同意', style: TextStyle(color: EsColors.ContentSecondary, fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal)),
            TextSpan(
                text: '《慧达人申请协议》',
                style: TextStyle(color: Color(0xff2589ff), fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    showDialog(
                      // 传入 context
                      context: context,
                      // 构建 Dialog 的视图
                      builder: (_) => Padding(
                        padding: EdgeInsets.all(16),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: <Widget>[
                            Container(
                              child: Padding(
                                padding: EdgeInsets.only(top: 8),
                                child: Center(
                                    child: Text(agreement_name,
                                        style: TextStyle(
                                          fontSize: 40.sp,
                                          color: Colors.black,
                                          decoration: TextDecoration.none,
                                        ))),
                              ),
                              color: Colors.white,
                            ),
                            Container(
                              alignment: Alignment.center,
                              color: Colors.white,
                              height: 800.w,
                              child: ListView(
                                children: [
                                  Column(
                                    children: <Widget>[
                                      Padding(
                                        padding: EdgeInsets.only(top: 15, bottom: 8),
                                        child: Html(
                                          data: html,
                                        ),
                                      )
                                    ],
                                  )
                                ],
                              ),
                            ),
                            Container(
                                color: Colors.white,
                                child: Column(children: [
                                  SizedBox(height: 20.w),
                                  GestureDetector(
                                    child: Center(
                                        child: Text(
                                      '确定',
                                      style: TextStyle(
                                        color: Colors.blue,
                                        fontSize: 40.sp,
                                        decoration: TextDecoration.none,
                                      ),
                                    )),
                                    onTap: () {
                                      Navigator.of(context).pop();
                                    },
                                  ),
                                  SizedBox(height: 20.w),
                                ]))
                          ],
                        ),
                      ),
                    );

                    print('《慧达人申请协议》');
                  })
          ]))
        ]),
      ),
    );
  }

  Widget _bottom() {
    return TextButton(
        onPressed: () {
          if (_nameController.text.trim().isEmpty ?? true) {
            toast('请填写姓名');
            return;
          }
          if (_phoneController.text.trim().isEmpty ?? true) {
            toast('请填写手机号');
            return;
          } else {
            if (!isChinaPhoneLegal(_phoneController.text)) {
              toast('请填写正确手机号');
              return;
            }
          }

          if (controller3.text.trim().isEmpty ?? true) {
            toast('请填写地址');
            return;
          }
          if (!_agree) {
            toast('请同意协议');
            return;
          }

          if (_higherPhoneController.text.trim().isEmpty ?? true) {
            YpShowDialog.normalConfirm(context, '确定不填写上级手机号？', normalOrder: false, leftCallback: () {
              print('下一步');
              getapplysubmit();
            });
          } else {
            print('下一步');
            getapplysubmit();
          }
        },
        child: Text(
          '下一步',
          style: TextStyle(color: EsColors.White, fontSize: EsSizes.LG, fontWeight: EsFontWeights.Normal),
        ),
        style: OutlinedButton.styleFrom(minimumSize: Size(MediaQuery.of(context).size.width - 70, 44), primary: EsColors.Primary, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(23)), backgroundColor: EsColors.Primary));
  }
}
